package com.hsmw.api.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Sets;
import com.hsmw.api.controller.pub.TencentPushUtils;
import com.hsmw.api.exception.ApiException;
import com.hsmw.api.mapper.*;
import com.hsmw.api.vo.*;
import com.hsmw.common.base.BasePage;
import com.hsmw.common.base.BaseService;
import com.htn.common.core.base.DataResponse;
import com.htn.common.core.constant.AuditStatusEnum;
import com.htn.common.core.constant.CommonConstants;
import com.htn.common.core.constant.UserTypeEnum;
import com.hsmw.domain.*;
import com.hsmw.domain.vo.DriverDetailVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.htn.common.core.constant.CommonConstants.ResponseStatus.FAIL;
import static com.htn.common.core.constant.CommonConstants.ResponseStatus.SUCCESS;


/**
 * @author WD
 */
@Service
@Transactional(isolation = Isolation.REPEATABLE_READ, propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class HsmwUserService extends BaseService<HsmwUserMapper, HsmwUser> {

	@Autowired
	private HsmwUserMapper hsmwUserMapper;


	@Autowired
	private HsmwItemService hsmwItemService;

	@Autowired
	private HsmwUserDriverMapper hsmwUserDriverMapper;

	@Autowired
	private HsmwPhoneBindService   hsmwPhoneBindService;

	@Autowired
	private HsmwLeasingCompanyService   hsmwLeasingCompanyService;

	@Autowired
	private SysUserRoleMapper sysUserRoleMapper;

	@Autowired
	private HsmwDriverUserMapper hsmwDriverUserMapper;


	@Autowired
	private HsmwForcemanItemMapper hsmwForcemanItemMapper;

	public HsmwUser findByUsername(String username) {
		QueryWrapper<HsmwDriverUser> queryWrapper = new QueryWrapper<>();
		queryWrapper.lambda().eq(HsmwDriverUser::getUsername, username);
		return hsmwDriverUserMapper.selectOne(queryWrapper);
	}



	/**
	 * list分页
	 *
	 * @param page
	 * @param hsmwUser
	 * @return
	 */
	public IPage<HsmwUser> getHsmwUserPage(IPage page, HsmwUser hsmwUser) {
		LambdaQueryWrapper<HsmwUser> queryWrapper = new LambdaQueryWrapper<>();
		if (!StrUtil.isBlank(hsmwUser.getName())) {
			queryWrapper.like(HsmwUser::getName, hsmwUser.getName());
		}
		if (!StrUtil.isBlank(hsmwUser.getUsername())) {
			queryWrapper.eq(HsmwUser::getUsername, hsmwUser.getUsername());
		}
		if (!StrUtil.isBlank(hsmwUser.getType())) {
			queryWrapper.eq(HsmwUser::getType, hsmwUser.getType());
		}
		if (!StrUtil.isBlank(hsmwUser.getItemId())) {
			queryWrapper.eq(HsmwUser::getItemId, hsmwUser.getItemId());
		}
		if (!StrUtil.isBlank(hsmwUser.getConstructionUnitId())) {
			String constructionUnitId = hsmwUser.getConstructionUnitId();
//			List<HsmwItem> hsmwItemList = hsmwItemService.list(Wrappers.lambdaQuery(HsmwItem.class).eq(HsmwItem::getConstructionUnitId, constructionUnitId));
//			queryWrapper.in(HsmwUser::getItemId, hsmwItemList.stream().map(HsmwItem::getId).collect(Collectors.toList()));
			queryWrapper.eq(HsmwUser::getConstructionUnitId, constructionUnitId);
		}
		IPage ipage = this.baseMapper.selectPage(page, queryWrapper.orderByDesc(HsmwUser::getCreateTime));
		return ipage;
	}

	/**
	 * 根据ID查询
	 *
	 * @param id
	 * @return
	 */
	public HsmwUser getHsmwUserById(String id) {
		LambdaQueryWrapper<HsmwUser> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(HsmwUser::getId, id);
		return hsmwUserMapper.selectOne(queryWrapper);
	}

	/**
	 * 新增或修改 逻辑删除
	 *
	 * @return
	 */
	public DataResponse saveOrUpdateHsmwUser(HsmwUser hsmwUser) {
		SysUserRole sysUserRole = new SysUserRole();
		if (StringUtils.isNotBlank(hsmwUser.getId())) {
			LambdaQueryWrapper<HsmwUser> lambdaQueryWrapper = new LambdaQueryWrapper();
			lambdaQueryWrapper.eq(HsmwUser::getUsername, hsmwUser.getUsername());
			HsmwUser existHsmwUser = hsmwUserMapper.selectOne(lambdaQueryWrapper);
			if (existHsmwUser != null && !Objects.equals(existHsmwUser.getId(), hsmwUser.getId())) {
				return  new DataResponse(CommonConstants.ResponseStatus.USER_IS_EXIST,"用户已注册");
			} else {
				hsmwUserMapper.updateById(hsmwUser);
				HsmwUser user = hsmwUserMapper.selectById(hsmwUser.getId());
				if(StringUtils.isNotBlank(hsmwUser.getRoleId()) && !StringUtils.equals(hsmwUser.getRoleId(),user.getRoleId())){
					sysUserRoleMapper.delete(new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId,hsmwUser.getId()));
					sysUserRole.setUserId(hsmwUser.getId());
					sysUserRole.setRoleId(hsmwUser.getRoleId());
					sysUserRoleMapper.insert(sysUserRole);
				}
			}
		} else {
			LambdaQueryWrapper<HsmwUser> lambdaQueryWrapper = new LambdaQueryWrapper();
			lambdaQueryWrapper.eq(HsmwUser::getUsername, hsmwUser.getUsername());
			HsmwUser existHsmwUser = hsmwUserMapper.selectOne(lambdaQueryWrapper);
			if (existHsmwUser == null) {
				hsmwUser.setEnabled(true);
				hsmwUser.setFlag(false);
				//hsmwUser.setPassword(bCryptPasswordEncoder.encode(Optional.ofNullable(hsmwUser.getPassword()).orElse("")));
				hsmwUserMapper.insert(hsmwUser);
				if(StringUtils.isNotBlank(hsmwUser.getRoleId())){
					sysUserRole.setUserId(hsmwUser.getId());
					sysUserRole.setRoleId(hsmwUser.getRoleId());
					sysUserRoleMapper.insert(sysUserRole);
				}
			} else {
				return new DataResponse(CommonConstants.ResponseStatus.USER_IS_EXIST,"用户已注册");
			}
		}
		return new DataResponse();
	}

	public List<HsmwUser> getHsmwUserSelect() {
		LambdaQueryWrapper<HsmwUser> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(HsmwUser::getEnabled, true);
		return hsmwUserMapper.selectList(queryWrapper);
	}



	public List<HsmwUser> getchooseForceManSelect(String itemId, String constructionUnitId) {
		HashSet<HsmwUser> resultSet = Sets.newHashSet();
		List<HsmwUser> hsmwUserList = hsmwUserMapper.selectList(Wrappers.lambdaQuery(HsmwUser.class)
				.eq(HsmwUser::getType, CommonConstants.UserRole.FOREMAN.name())
				.eq(HsmwUser::getConstructionUnitId, constructionUnitId));
		if (!StrUtil.isEmpty(itemId)) {
			List<HsmwUser> itemUsers = hsmwUserMapper.selectList(Wrappers.lambdaQuery(HsmwUser.class)
					.eq(HsmwUser::getItemId, itemId));
			hsmwUserList.addAll(itemUsers);
		}
		return hsmwUserList.stream().distinct().collect(Collectors.toList());
	}

	public List<String> queryRecentsAddresslist(HashMap param) {
		return hsmwUserMapper.queryRecentsAddresslist(param);
	}


	public DataResponse getVirtualTelephony(CallVO callVO) {
		HashMap result = new HashMap();
		List<String> phones = new ArrayList<>();
		phones.add(callVO.getForemanLinkTel());
		phones.add(callVO.getDriverTelphoneNum());
		List<HsmwPhoneBind> binds = hsmwPhoneBindService.list(new LambdaQueryWrapper<HsmwPhoneBind>()
				.eq(HsmwPhoneBind::getOrderId,callVO.getOrderId())
				.in(HsmwPhoneBind::getPhoneFirst,phones)
				.in(HsmwPhoneBind::getPhoneSecond, phones));
				/*.and(wrapper -> wrapper.eq(HsmwPhoneBind::getPhoneFirst,callVO.getDriverTelphoneNum())
				.or().eq(HsmwPhoneBind::getPhoneSecond,callVO.getForemanLinkTel())));*/
		if(CollectionUtil.isNotEmpty(binds)){
			HsmwPhoneBind bind =binds.get(0);
			result.put("driverTel",bind.getSecretNo());
			return  new DataResponse(result);
		}else {
			XuniTelNumVO param = new XuniTelNumVO();
			param.setPhoneA(callVO.getDriverTelphoneNum());
			param.setPhoneB(callVO.getForemanLinkTel());
			XuniTelNumVO vo = IACasClientUtils.bindAxb(param);
			if(StringUtils.isBlank(vo.getSecretNo())){
				return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"获取虚拟号码失败，原因："+vo.getResult()+"！");
			}
			HsmwPhoneBind phoneBind = new HsmwPhoneBind();
			phoneBind.setPhoneFirst(callVO.getDriverTelphoneNum());
			phoneBind.setPhoneSecond(callVO.getForemanLinkTel());
			phoneBind.setSecretNo(vo.getSecretNo());
			phoneBind.setSubSid(vo.getSubsId());
			phoneBind.setOrderId(callVO.getOrderId());
			hsmwPhoneBindService.save(phoneBind);
			result.put("driverTel",vo.getSecretNo());
			return  new DataResponse(result);
		}
	}

	public DataResponse getDriverVirtualTelephony(DriverCallVO callVO) {
		HashMap result = new HashMap();
		List<String> phones = new ArrayList<>();
		phones.add(callVO.getFromPhoneNum());
		phones.add(callVO.getToPhoneNum());
		List<HsmwPhoneBind> binds = hsmwPhoneBindService.list(new LambdaQueryWrapper<HsmwPhoneBind>()
				.in(HsmwPhoneBind::getPhoneFirst,phones)
				.in(HsmwPhoneBind::getPhoneSecond, phones)
				.eq(HsmwPhoneBind::getOrderId,callVO.getOrderId()));
				/*.and(wrapper -> wrapper.eq(HsmwPhoneBind::getPhoneFirst,callVO.getDriverTelphoneNum())
				.or().eq(HsmwPhoneBind::getPhoneSecond,callVO.getForemanLinkTel())));*/
		if(CollectionUtil.isNotEmpty(binds)){
			HsmwPhoneBind bind =binds.get(0);
			result.put("driverTel",bind.getSecretNo());
			return  new DataResponse(result);
		}else {
			XuniTelNumVO param = new XuniTelNumVO();
			param.setPhoneA(callVO.getFromPhoneNum());
			param.setPhoneB(callVO.getToPhoneNum());
			XuniTelNumVO vo = IACasClientUtils.bindAxb(param);
			if(StringUtils.isBlank(vo.getSecretNo())){
				return  new DataResponse(CommonConstants.ResponseStatus.VALIDATE_FAILED,"获取虚拟号码失败，原因："+vo.getResult()+"！");
			}
			HsmwPhoneBind phoneBind = new HsmwPhoneBind();
			phoneBind.setPhoneFirst(callVO.getFromPhoneNum());
			phoneBind.setPhoneSecond(callVO.getToPhoneNum());
			phoneBind.setSecretNo(vo.getSecretNo());
			phoneBind.setSubSid(vo.getSubsId());
			phoneBind.setOrderId(callVO.getOrderId());
			hsmwPhoneBindService.save(phoneBind);
			result.put("driverTel",vo.getSecretNo());
			return  new DataResponse(result);
		}
	}





    public void saveOrUpdateUser(HsmwUser hsmwUser) {
		if(StringUtils.isNotBlank(hsmwUser.getId())){
			hsmwUser.setEnabled(true);
			hsmwUserMapper.updateById(hsmwUser);
			HsmwUserDriver hsmwUserDriver = hsmwUserDriverMapper.selectOne(new LambdaQueryWrapper<HsmwUserDriver>().eq(HsmwUserDriver::getUserId, hsmwUser.getId()));
			hsmwUserDriver.setMyPicture(hsmwUser.getQueryParam());
			hsmwUserDriverMapper.updateById(hsmwUserDriver);
		}else {
			hsmwUserMapper.insert(hsmwUser);
		}
	}

	public void saveOrUpdateForemanInfo(HsmwUser hsmwUser) {
		if(StringUtils.isNotBlank(hsmwUser.getId())){
			hsmwUser.setEnabled(true);
			hsmwUserMapper.updateById(hsmwUser);
		}
		//HsmwUser userInfo = hsmwUserMapper.selectById(hsmwUser.getId());
/*		if(UserTypeEnum.SELFRUN.getValue().equals(userInfo.getType())){
			HsmwLeasingCompany company = hsmwLeasingCompanyService.getOne(new LambdaQueryWrapper<HsmwLeasingCompany>()
					.eq(HsmwLeasingCompany::getUserId,userInfo.getId()));
			if(StringUtils.isNotBlank(hsmwUser.getName())){
				company.setLinkMan(hsmwUser.getName());
			}
			if(StringUtils.isNotBlank(hsmwUser.getUsername())){
				company.setTel(hsmwUser.getUsername());
			}
			hsmwLeasingCompanyService.updateById(company);
		}*/

	}


	public void deleteHsmwUserById(String id) {
		hsmwUserMapper.deleteById(id);
	}



    public List<HsmwUser> itme_user_list(LambdaQueryWrapper<HsmwUser> eq) {
		return  hsmwUserMapper.itme_user_list();

    }
}
